<script setup lang="tsx">
  import { NButton, NPopconfirm, NTag } from 'naive-ui';
  import { fetchDeleteVoice, fetchGetEvent } from '@/service/api';
  import { $t } from '@/locales';
  import { useAppStore } from '@/store/modules/app';
  import {
    fromStatusRecord,
    operationStatusRecord,
    userGenderRecord,
  } from '@/constants/business';
  import { formatDate, handleCopy, isPermission } from '@/utils/tools';
  import { useTable, useTableOperate } from '@/hooks/common/table';
  import type { Api } from '@/typings/api';
  import UserOperateDrawer from './modules/user-operate-drawer.vue';
  import UserSearch from './modules/user-search.vue';
  const appStore = useAppStore();

  const {
    columns,
    columnChecks,
    data,
    getData,
    getDataByPage,
    loading,
    mobilePagination,
    searchParams,
    pagination,
    resetSearchParams,
  } = useTable({
    apiFn: fetchGetEvent,
    showTotal: true,
    apiParams: {
      pageNum: 1,
      pageSize: 10,
    },
    columns: () => [
      {
        type: 'selection',
        align: 'center',
        width: 48,
      },
      {
        key: 'index',
        title: $t('common.index'),
        align: 'center',
        width: 64,
      },
      {
        key: 'method',
        title: $t('page.systemControl.operationApi.method'),
        align: 'center',
        width: 100,
      },
      {
        key: 'url',
        title: $t('page.systemControl.operationApi.url'),
        align: 'center',
        width: 150,
      },
      {
        key: 'operatorId',
        title: $t('page.systemControl.operationApi.operateUserId'),
        align: 'center',
        minWidth: 50,
        render: (row: any) => {
          const text = {
            id: row.operatorId,
          };
          return (
            <>
              <span>{text?.id ?? ''}</span>
              {text?.id && (
                <icon-local-copy
                  style="cursor: pointer;"
                  onClick={() => handleCopy(text?.id)}
                />
              )}
            </>
          );
        },
      },
      {
        key: 'type',
        title: $t('page.systemControl.operationApi.name'),
        align: 'center',
        width: 100,
        render: (row: any) => {
          const tagMap: Record<Api.User.operationStatus, NaiveUI.ThemeColor> = {
            // 'default' | 'error' | 'primary' | 'info' | 'success' | 'warning';
            add: 'default',
            update: 'primary',
            delete: 'error',
            select: 'warning',
            login: 'success',
          };
          let boo = true;
          let label = '';
          if (
            row.type !== 'add' &&
            row.type !== 'update' &&
            row.type !== 'delete' &&
            row.type !== 'select' &&
            row.type !== 'login'
          ) {
            label = $t('page.systemControl.operationApi.any');
            boo = false;
          } else {
            label = $t(
              operationStatusRecord[row.type as Api.User.operationStatus]
            );
          }

          return (
            <NTag
              type={
                boo ? tagMap[row.type as Api.User.operationStatus] : 'error'
              }
            >
              {label}
            </NTag>
          );
        },
      },
      {
        key: 'description',
        title: $t('page.systemControl.operationApi.description'),
        align: 'center',
        minWidth: 50,
        // render: (row: any) => {
        //   const text = JSON.parse(row.metadata)?.description ?? '';
        //   return text;
        // },
      },
      {
        key: 'sufferOperatorId',
        title: $t('page.systemControl.operationApi.operateId'),
        align: 'center',
        minWidth: 50,
        render: (row: any) => {
          const text = {
            id: row.sufferOperatorId,
          };
          return (
            <>
              <span>{text?.id ?? ''}</span>
              {text?.id && (
                <icon-local-copy
                  style="cursor: pointer;"
                  onClick={() => handleCopy(text?.id)}
                />
              )}
            </>
          );
        },
      },
      {
        key: 'createdAt',
        title: $t('page.userData.userList.createdAt'),
        align: 'center',
        minWidth: 100,
        render: (row: any) => {
          return formatDate(row.createdAt, 'YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        key: 'operate',
        title: $t('common.operate'),
        align: 'center',
        width: 200,
        render: (row: any) => (
          <div class="flex-center gap-8px">
            {row.event.length > 0 && (
              <NButton
                type="primary"
                ghost
                size="small"
                onClick={() => details(row.id)}
              >
                {$t('common.details')}
              </NButton>
            )}
            {/* <NButton type="primary" v-if="isPermission()" ghost size="small" onClick={() => edit(row.id)}>
            {$t('common.edit') }
          </NButton> */}
            {/* <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm> */}
          </div>
        ),
      },
    ],
  });

  const {
    drawerVisible,
    operateType,
    editingData,
    detailData,
    handleAdd,
    handleEdit,
    handleDetails,
    checkedRowKeys,
    onBatchDeleted,
    onDeleted,
    // closeDrawer
  } = useTableOperate(data, getData);

  async function handleBatchDelete() {
    // request

    onBatchDeleted();
  }

  async function handleDelete(id: number) {
    // request
    const { data }: any = await fetchDeleteVoice({
      id,
      deletedAt: new Date(),
    });

    if (data.status === 200) {
      onDeleted();
    } else {
      onDeleted(false, data.message);
    }
  }

  function edit(id: number) {
    handleEdit(id);
  }

  function details(id: number) {
    handleDetails(id);
  }

  // 重置筛选
  const resetSearch = () => {
    searchParams.operatorId = '';
  };
</script>

<template>
  <div
    class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto"
  >
    <UserSearch
      v-model:model="searchParams"
      @reset="resetSearch"
      @search="getDataByPage"
    />
    <NCard
      :title="$t('page.systemControl.operationApi.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
    >
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="(row: any) => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <UserOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="detailData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
